package com.szsh.aiot.hsm.service.impl;

import com.szsh.aiot.common.core.domain.AjaxResult;
import com.szsh.aiot.common.utils.TimeTools;
import com.szsh.aiot.hsm.domain.camera.AbnormalLogin;
import com.szsh.aiot.hsm.domain.camera.UserLoginModel;
import com.szsh.aiot.hsm.service.LoginService;
import com.szsh.aiot.hsm.utils.Hash163;
import org.apache.commons.lang3.StringUtils;
import org.influxdb.dto.Query;
import org.influxdb.impl.InfluxDBMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Date 2023/10/24: 10:02
 * @Author: LOADING>>>>>
 */

@Service
public class LoginServiceImpl implements LoginService {

    public static final Logger LOGGER = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Value("${hsm.camera.unnormal-vality:}")
    private int unnormalVality;

    @Autowired
    private Hash163 hash;

    @Autowired
    private InfluxDBMapper influxMapper;

    @Override
    public AjaxResult getUserLoginInfos(String phone) throws Exception {
        List<UserLoginModel> modelList = new ArrayList<>();
        List<AbnormalLogin> logins = getAbnormalLogin(phone,unnormalVality);
        logins.forEach(info -> {
            try {
                modelList.add(getUserLoginModel(info));
            } catch (Exception e) {
                LOGGER.error("获取账号登录提醒数据时发生异常{}", phone, e);
            }
        });
        return AjaxResult.success(modelList);
    }

    private UserLoginModel getUserLoginModel(AbnormalLogin userLogininfo) {
        UserLoginModel model = new UserLoginModel();
        Date loginTime = Date.from(userLogininfo.getTime());
        model.setTime(TimeTools.date2String(loginTime, "yyyy-MM-dd HH:mm"));
        long days = TimeTools.getDaysBetween(loginTime, TimeTools.getNow());
        String dayStr = "";
        if (days == 1) {
            dayStr = "今天";
        } else if (days == 2) {
            dayStr = "昨天";
        } else {
            dayStr = "前天";
        }
        model.setDate(dayStr);
        String origin = "";
        if (!StringUtils.isEmpty(userLogininfo.getProvince())) {
            origin = origin + userLogininfo.getProvince();
        }
        if (!StringUtils.isEmpty(userLogininfo.getCity())) {
            origin = origin + userLogininfo.getCity();
        }
        if (!StringUtils.isEmpty(userLogininfo.getDevice())) {
            origin = origin + " " + userLogininfo.getDevice();
        }
        model.setOrigin(origin);
        return model;
    }


    /**
     * 查询vality天内的异常登录信息
     *
     * @param phone
     * @param vality
     * @return
     */
    public List<AbnormalLogin> getAbnormalLogin(String phone, int vality) throws Exception {
        StringBuilder querySB = new StringBuilder();
        querySB.append("select * from abnormal_login where hashPhone='").append(hash.sHash(phone))
                .append("' and phone='").append(phone).append("'");
        querySB.append(" and time>now()-").append(vality)
                .append("d order by time desc tz('Asia/Shanghai')");
        LOGGER.info("abnormal influxDB query:{}", querySB.toString());
        Query query = new Query(querySB.toString());
        return influxMapper.query(query, AbnormalLogin.class);
    }


}
